<template>
    <el-card class="container">
        <el-row type="flex" justify="space-between" align="middle" class="custom-banner">
            <el-button v-if="tableData.length !== 0" @click="delPageData" style="margin-bottom: 10px;" plain
                type="danger">删除该表数据</el-button>
            <div class="header">
                <div style="float: left; display: flex; width: 20%;">
                    <img style=" width: 20%; height: 20%;" src="/public/paperAnalysis.png" alt="">
                    <span>试卷分析</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style=" width: 20%; height: 20%;" src="/public/teacher.png" alt="">
                    <span>教师：{{ username }}</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="   width: 20%; height: 20%;" src="/public/course.png" alt="">
                    <span>课程：{{ subject }}</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="   width: 20%; height: 20%;" src="/public/class.png" alt="">
                    <span>班级：{{ class_name }}</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="  width: 20%; height: 20%;" src="/public/academy.png" alt="">
                    <span>学院：{{ teaching_academy }}</span>
                </div>
            </div>
        </el-row>
        <div>
            <el-table height="450" class="custom-table" :spanMethod="spanMethod" v-if="tableData.length"
                :data="tableData" stripe style="width: 100%" border="vertical">
                <el-table-column v-for="(header, index) in headers" :key="header" :prop="header" :label="header"
                    v-bind="index === 0 ? { fixed: 'left' } : {}">
                </el-table-column>
            </el-table>
            <div v-if="tableData.length" class="outerBox">
                <div class="extraTableContainer">
                    <table>
                        <thead>
                            <tr>
                                <th>类型</th>
                                <th v-for="col in numCols" :key="col">{{ col }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(data, dataType) in extraTableData" :key="dataType">
                                <td>{{ dataType }}</td>
                                <td v-for="value in data" :key="value">{{ value }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>


            <!-- <div class="table-container">
                <table v-if="tableData.length" class="responsive-table" border="1">
                    <thead>
                        <tr style="background-color: #f2f2f2;">
                            <th v-for="(header, index) in headers" :key="index" :colspan="colspans[index] || 1">{{
                                header }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, rowIndex) in tableData" :key="rowIndex">
                            <td v-for="(header, colIndex) in headers" :key="colIndex"
                                v-if="shouldRenderCell(colIndex, rowIndex)" :colspan="getColspan(colIndex, rowIndex)">
                                {{ item[header] }}
                            </td>
                        </tr>
                    </tbody>

                </table>
            </div> -->
        </div>
        <el-card class="chartsGroup">
            <template v-if="tableData.length" #default>
                <div class="chartsStyle">
                    <div>
                        <pieWithGap></pieWithGap>
                    </div>
                    <div style="margin-top: 20px;">
                        <basicColumnChart></basicColumnChart>
                    </div>
                    <div style="margin-top: 20px;">
                        <Horizontal_columnChart></Horizontal_columnChart>
                    </div>
                </div>
            </template>
            <el-card>
                <div style="display: flex; justify-content: space-around;height: 70vh;">
                    <div class="leftBox">
                        <p style="color: red;font-style: italic;font-size: 35px;word-break: break-all;">
                            请下载模板，根据模板填写好分数后再上传分数!
                        </p>
                        <el-card style="width: 100%;">
                            <h1 style="height: 5%;font-size: 40px; text-align: center;">下载模板</h1>
                            <div class="btGroup_1"
                                style="height: 10vh; display: flex; justify-content: space-around;align-items: center;">
                                <el-button style="font-size: 30px;border: none;"
                                    @click="getExcelTable('A')">下载A卷模板</el-button>
                                <el-button style="font-size: 30px;border: none;" size="large"
                                    @click="getExcelTable('B')">下载B卷模板</el-button>
                            </div>
                        </el-card>
                    </div>
                    <el-card style="width: 50%; height: 100%;">
                        <h1 style="font-size: 40px; text-align: center;">上传文件</h1>
                        <Analysis_Implement @updateData="handleUpdateData" />
                    </el-card>
                </div>
            </el-card>
        </el-card>
    </el-card>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import Analysis_Implement from './Analysis_Implement.vue'
import pieWithGap from '@/components/pieWithGap.vue'
import Horizontal_columnChart from '@/components/Horizontal_columnChart.vue'
import { autoMakeXlsx_api } from '@/api/target_item_info_input'
const tableData = ref([]);
const headers = ref([]);
import eventBus from '/eventBus';
import basicColumnChart from '@/components/basicColumnChart.vue'
import { useClassStore } from '@/stores/modules/class'
import { useUserStore } from '@/stores/modules/user'
const classStore = useClassStore()
const UserStore = useUserStore()
const acs_id = classStore.classInfo.user_and_acs_id
const username = UserStore.userInfo.username
// 定义表头的列数
const colsForTable = ref();
// 根据colsForTable生成列的数组
const numCols = computed(() => {
    const columns = [];
    for (let i = 1; i <= colsForTable.value; i++) {
        columns.push(i);
    }
    return columns;
});
// 定义类别列的数据
// const categories = ['平均值', '最大值', '最小值', '方差'];

// 生成随机数据
// const generateRandomNumber = () => Math.floor(Math.random() * 100) + 1;

// 生成表格数据
// const tableData_1 = ref([]);
// for (let i = 0; i < colsForTable.value; i++) {
//     tableData_1.value.push(generateRandomNumber());
// }
const class_name = classStore.classInfo.class_name
const subject = classStore.classInfo.subject
const teaching_academy = classStore.classInfo.teaching_academy
const extraTableData = ref()
// const temData = ref([])
// 将四组数据合并为一个对象
// const extraTableData_render = computed(() => {
//     console.log("temData.value", temData.value);
//     const avgValues = temData.value.map(obj => obj.avg);
//     const maxValues = temData.value.map(obj => obj.max);
//     const minValues = temData.value.map(obj => obj.min);
//     const varianceValues = temData.value.map(obj => obj.variance);

//     const mergedData = reactive({
//         '平均值': avgValues,
//         '最大值': maxValues,
//         '最小值': minValues,
//         '方差': varianceValues
//     });

//     return mergedData;
// });
// 组件挂载时尝试从LocalStorage加载数据
onMounted(() => {
    console.log("onMounted");
    loadFromLocalStorage();

    // console.log("temData", temData.value);
});
import { useRoute } from 'vue-router';
const route = useRoute();
const subId = parseInt(route.params.subId);
// 记录已经合并过的单元格范围
const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (rowIndex < 2) { // 只对前两行进行处理
        if (row[column.property]) { // 当前单元格非空
            let span = 1; // 初始化合并列数
            // 检查后续单元格直到非空或行末
            for (let i = columnIndex + 1; i < headers.value.length; i++) {
                if (!tableData.value[rowIndex][headers.value[i]]) {
                    span++; // 后续空单元格，增加合并数
                } else {
                    break; // 遇到非空单元格，停止计数
                }
            }
            if (span > 1) {
                return [1, span]; // 返回合并的行数和列数
            }
        } else {
            // 检查当前单元格是否应该被合并到前一个单元格
            for (let i = columnIndex - 1; i >= 0; i--) {
                if (tableData.value[rowIndex][headers.value[i]]) { // 找到最近的非空单元格
                    // 检查这个非空单元格是否已经计算过合并
                    let span = 1;
                    for (let j = i + 1; j < headers.value.length; j++) {
                        if (!tableData.value[rowIndex][headers.value[j]]) {
                            span++;
                        } else {
                            break;
                        }
                    }
                    if (columnIndex < i + span) {
                        return [0, 0]; // 当前单元格应该被合并，不单独渲染
                    } else {
                        break; // 当前单元格不应该被合并到前一个单元格
                    }
                }
            }
        }
    }
    return [1, 1]; // 默认不合并，单独渲染
};



const getExcelTable = async (paperType) => {
    try {
        const response = await autoMakeXlsx_api(paperType, acs_id);
        // 提取buffer数据
        const buffer = response.data.content.data;

        // 创建Blob对象
        const blob = new Blob([new Uint8Array(buffer)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });

        // 创建一个URL链接，指向响应体的blob
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        // 从响应头中提取文件名，或者如果没有则指定默认的文件名
        const contentDisposition = response.headers['content-disposition'];
        // let filename = 'output.xlsx';
        let filename = `${paperType}卷模板.xlsx`;
        if (contentDisposition) {
            const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = filenameRegex.exec(contentDisposition);
            if (matches != null && matches[1]) {
                filename = matches[1].replace(/['"]/g, '');
            }
        }
        link.setAttribute('download', filename);

        // 触发下载
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('下载Excel文件失败:', error);
    }
}
const handleUpdateData = (json, extraTableData_1) => {
    // console.log("extraTableData", extraTableData);
    extraTableData.value = extraTableData_1
    // console.log("extraTableData", extraTableData.value);
    // Object.entries(extraTableData.value).forEach(([key, value]) => {
    //     value.forEach(item => {
    //         temData.value.push(item)
    //     })
    // });
    headers.value = json[2];
    const regularData = json.slice(3).map(row => {
        const rowData = {};
        row.forEach((cell, index) => rowData[headers.value[index]] = cell);
        return rowData;
    });
    const specialData = json.slice(0, 2).map(row => {
        const specialRowData = {};
        headers.value.forEach((header, index) => specialRowData[header] = row[index] || '');
        return specialRowData;
    });
    tableData.value = specialData.concat(regularData);

    // 保存数据到 LocalStorage
    saveToLocalStorage();
};
const delPageData = () => {
    localStorage.removeItem(`uploadedData${acs_id}`);
    // localStorage.removeItem('computedDataForExtraTable');
    localStorage.removeItem(`computedDataForExtraTable${acs_id}`);
    eventBus.methods.clearLocalStorage()
    location.reload(true);
}
// 保存数据到LocalStorage
const saveToLocalStorage = () => {
    const dataToStore = {
        headers: headers.value,
        tableData: tableData.value
    };
    // const newExtraTableData = {};
    // Object.entries(extraTableData.value).forEach(([key, value], index) => {
    //     // 使用索引值加1作为新的键，原始值作为新对象的值
    //     newExtraTableData[index + 1] = value;
    // });

    // 将新对象赋值给 extraTableData.value
    // extraTableData.value = newExtraTableData;
    const dataToStore_extraTable = extraTableData.value
    Object.entries(dataToStore_extraTable).map(([key, val])=>{
        colsForTable.value = val.length
    })
    console.log("dataToStore_extraTable", dataToStore_extraTable);
    localStorage.setItem(`uploadedData${acs_id}`, JSON.stringify(dataToStore));
    localStorage.setItem(`computedDataForExtraTable${acs_id}`, JSON.stringify(dataToStore_extraTable));
};
// 从LocalStorage加载数据
const loadFromLocalStorage = () => {
    const storedData = localStorage.getItem(`uploadedData${acs_id}`);
    const extraTableData_1 = localStorage.getItem(`computedDataForExtraTable${acs_id}`);
    if (storedData) {
        const { headers: storedHeaders, tableData: storedTableData } = JSON.parse(storedData);
        headers.value = storedHeaders;
        tableData.value = storedTableData;
        Object.entries(JSON.parse(extraTableData_1)).map(([key, val]) => {
            colsForTable.value = val.length
        })
        // extraTableData.value = extraTableData_1
        extraTableData.value = JSON.parse(extraTableData_1)
        // 在加载数据后，将 extraTableData 的值赋给 temData
        // console.log("extraTableData.value__kzy", extraTableData.value);
    }
    // if (extraTableData_1) {

    //     // Object.entries(extraTableData.value).forEach(([key, value]) => {
    //     //     console.log("value", value);
    //     //     value.forEach(item => {
    //     //         temData.value.push(item)
    //     //     })
    //     // });
    // }
};

</script>
<style lang="scss" scoped>
$table-max-height: 400px; // 表格容器的最大高度
.wide {
    width: 320px;
}
table {
    border-collapse: collapse;
    margin: 25px 0;
    font-size: 0.9em;
    font-family: sans-serif;
    min-width: 400px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}

th,
td {
    // border: 1px solid black;
    // padding: 8px;
    text-align: center;
    padding: 12px 15px;
    border: 1px solid #dddddd;
}

th {
    background-color: #009879;
    color: #ffffff;
}

tr:hover {
    background-color: #f3f3f3;
}
.container {
    // max-width: 2500px;
    max-width: 100%;
    .custom-banner {
        color: white;
        margin-bottom: 20px;

        .header {
            width: 100%;
            background-color: rgba(95, 214, 217, 0.5);
            background-color: #d9e8fc;
            // background-color: #e5f5fe;
            color: #64748b;
            text-align: center;
            height: 10vh;
            // justify-content: center;
            display: flex;
            // line-height: 100px;
            align-items: center;
            // font-size: 16px;
            // font-size: $global-font-size;
            font-family: Arial, sans-serif;
            border-radius: 5px;
            border-left: 5px solid #60a5fa;
            border-top: none;
            border-right: none;
            border-bottom: none;
            margin-bottom: 10px;
            padding-right: 20px;

            span {
                display: flex;
                // height: 10px;
                // line-height: 10px;
                align-items: center;
            }
        }
    }
    .custom-table {
        // background-color: #60a5fa;
        margin-bottom: 20px;
        &::v-deep {
                background-color: #e5f5fe;
                // padding: 5px;
                .el-table__header-wrapper tr th {
                    // background-color: rgb(194, 212, 238) !important;
                    color: black;
                    text-align: center;
                }
        
                // .el-table__body-wrapper th {
                //     background-color: rgb(128, 26, 26);
                //     color: red;
                // }
                td,
                th {
                    text-align: center;
                    border-color: black;
                }
        
                .el-table__cell {
                    background-color: #d9e8fc;
                }
                                  &::-webkit-scrollbar {
                                      width: 40px;
                                      /* 纵向滚动条*/
                                      height: 50px;
                                      /* 横向滚动条 */
                                      background-color: transparent;
                                  }
                .el-table__body-wrapper::-webkit-scrollbar {
                    width: 10px;
                    /* 滚动条宽度 */
                }

                .el-table__body-wrapper::-webkit-scrollbar-track {
                    background: #f5f5f5;
                    /* 滚动条轨道背景色 */
                }

                .el-table__body-wrapper::-webkit-scrollbar-thumb {
                    background: #888;
                    /* 滚动条手柄背景色 */
                }
                    
            }
    }
    .outerBox{
        box-sizing: border-box;
        // width: 70%;
        width: 100%;
        display: flex;
        justify-content: center;
        .extraTableContainer {
        // width: 100%;
        // display: flex;
        // justify-content: center;
        margin-bottom: 20px;
        overflow-x: scroll;
        // text-align: center;
        // margin: 0 auto;
    }
    }
    

    .chartsGroup {
        // margin-top: 30px;
        background-color: #d9e8fc;
        border: 3px solid #60a5fa;

        .chartsStyle {
            overflow-x: auto;
            // max-width: 3000px;
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            align-items: center;
        }
    }
}

:deep().el-scrollbar {
    --el-scrollbar-opacity:1;
    --el-scrollbar-bg-color: rgb(151, 144, 144);
    --el-scrollbar-hover-opacity: 1;
    --el-scrollbar-hover-bg-color: rgb(151, 144, 144);
}

</style>
